//wedo wexin

var request = require("superagent");
var q = require("q");
var sign = require("./helper");

//应该是7200，考虑其他延时，少放一些
var token_expires_in = 7190*1000;
var ticket_expires_in = 7190*1000;

var token_info = {access_token:"",createtime:new Date()};
var ticket_info = {access_ticket:"",createtime:new Date()};

var wx_api_urls = {
  token_url:"https://api.weixin.qq.com/cgi-bin/token",
  //网页授权access_token
  sns_token_url:"https://api.weixin.qq.com/sns/oauth2/access_token",
  callback_ip:"https://api.weixin.qq.com/cgi-bin/getcallbackip",
  ticket_url:"https://api.weixin.qq.com/cgi-bin/ticket/getticket"
}

function WechatAPI(appID ,appsecret){
  if(!(this instanceof WechatAPI)){
    return new WechatAPI(appID,appsecret);
  }
  this.appID = appID;
  this.appsecret = appsecret;
}

/**
* @synopsis 签名算法 
*
* @param jsapi_ticket 用于签名的 jsapi_ticket
* @param url 用于签名的 url ，注意必须动态获取，不能 hardcode
* @returns
*/
WechatAPI.prototype.generate_js_sign = function (url) {
  var deferred = q.defer();
  this.get_ticket().then(function(ticket){
    var ret = sign.sign(ticket,url);
    deferred.resolve(ret);
  }).fail(function(err){
    deferred.reject(new Error(err) );
  });
  return deferred.promise;
};

/**
 *获取auth2.0时所有的access_token
 **/
WechatAPI.prototype.get_sns_token = function(code){
	var deferred = q.defer();
	request.get(wx_api_urls.sns_token_url)
		.query({appid:this.appID,secret:this.appsecret,code:code,grant_type:"authorization_code"})
        .set({"Content-Type": 'application/json' })
		.end(function(err,res){
			//console.log(res.text);
			if(err){
			   	deferred.reject(new Error(err));
			}else{
				//console.log("SNS access_token body is ",res.text);
				var result = JSON.parse(res.text);
				if(!result.access_token){
					deferred.reject(new Error(result.errcode + "," + result.errmsg));
				}else{
					deferred.resolve(result);
				}
			}
	});
	return deferred.promise;
};

/*
获取基础支持的TOKEN，有效期为7200秒
*/
WechatAPI.prototype.get_token = function(){
    var deferred = q.defer();
    var currentTimeStamp = new Date();
    //console.log("token_info is ",token_info);
    if( token_info.access_token && (currentTimeStamp - token_info.createtime) < token_expires_in){
      deferred.resolve( token_info.access_token );
    }else{
      request.get(wx_api_urls.token_url)
       .query({grant_type:"client_credential",appid:this.appID,secret:this.appsecret})
       .set({"Content-Type": 'application/json' })
       .end(function(err,res){
            //console.log(err,res);
            if(err){
                deferred.reject(new Error(err));
            }else{
                token_info.access_token = res.body.access_token;
                token_info.createtime = new Date();
                deferred.resolve(token_info.access_token);
            }
      });
    }
    return deferred.promise;
};

/*获取JSSDK调用时需要使用的ticket，有效期为7200秒，后续应该添加缓存，因为规定时间内有调用次数限制*/
WechatAPI.prototype.get_ticket = function(){
    var deferred = q.defer();
    var currentTimeStamp = new Date();
    if( ticket_info.access_ticket && (currentTimeStamp - ticket_info.createtime) < ticket_expires_in){
      deferred.resolve( ticket_info.access_ticket );
    }else{
        this.get_token().then(function(access_token){
        request.get(wx_api_urls.ticket_url)
          .query({access_token:access_token,type:"jsapi"})
          .set({"Content-Type": "application/json" })
          .end(function(err,res){
                if(err){
                    deferred.reject(new Error(err));
                }else{
                    //console.log(res.body);
                    ticket_info.access_ticket = res.body.ticket;
                    ticket_info.createtime = new Date();
                    deferred.resolve(res.body.ticket);
                }
            })
        });
    }
    return deferred.promise;
};

/*返回微信服务器的地址列表*/
WechatAPI.prototype.get_callback_ip=function(){
    var deferred = q.defer();
    this.get_token().then(function(access_token){
        request.get(wx_api_urls.callback_ip)
           .query({access_token:access_token})
           .end(function(err,res){
                if(err){
                    deferred.reject(new Error(err));
                }else{
                    deferred.resolve(res.body);
                }
        });
    }).fail(function(err){
        deferred.reject(err);
    });
    return deferred.promise;
}

exports.WechatAPI = WechatAPI;
//module.exports = WechatAPI;
